/* 
 * Copyright (c)	Insighten Intelligent Equipment co.,LTD
 * 
 *  Use of this software is controlled by the terms and conditions found
 *  in the license agreement under which this software has been supplied.
 * 
 */
/** 
 * @file tcp_cli_main.c
 * @brief test for tcp client library, need librwbuf.a and libtcp_client.a
 * @author taco [tacoee@gmail.com]
 * @version 0.1
 * @date 2010-09-03
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include "tcp_client.h"
#include "rwbuf.h"

static void helper(char *pro)
{
	fprintf(stderr, "Usage: %s host_address[ip] port[1234] test_message[\"string\"]\n", pro);
}

int main(int argc, char *argv[])
{
	int port;
	char *host_name;
	TcpClient *client = NULL;
	SocketAttr attr={0,8192};
	RwBuf	*buf;
	int ret;
	char *msg;
	int maxfd;

	fd_set rset;
	fd_set wset;

	FD_ZERO(&rset);
	FD_ZERO(&wset);


	if (argc < 4) {
		helper(argv[0]);
		exit(1);
	}
	host_name = argv[1];
	port = atol(argv[2]);
	msg = argv[3];

	printf("host name %s\n", argv[1]);
	printf("port %d\n", port);
	printf("message %s\n", msg);

	buf = buf_new((FunMemAlloc)NULL, (FunMemFree)NULL);
	buf_init(buf, 8192);

	memcpy(buf->mem, msg, strlen(msg));
	buf->wpos += strlen(msg);

	client = tcp_client_new();

	tcp_client_init(client, port, host_name, &attr, buf);
	tcp_client_create(client);

	do {
		ret = tcp_client_connect(client);
	} while(ret != RET_OK);

	maxfd = client->fd;
	FD_SET(client->fd, &wset);

	while(1) {
		ret = select(maxfd+1, &rset, &wset, NULL, NULL);

		if (FD_ISSET(client->fd, &wset)) {
			ret = tcp_client_wirte(client, strlen(msg));
			client->buf->rpos += ret;

			if (ret == strlen(msg)) {
				memset(client->buf->mem, 0, client->buf->wpos);
				client->buf->wpos = 0;
				FD_CLR(client->fd, &wset);
				FD_SET(client->fd, &rset);
			}
		}
		if (FD_ISSET(client->fd, &rset)) {
			ret = tcp_client_read(client, 15);
			if (ret >= 0 ) {
				client->status = DONE;
				client->buf->wpos +=ret;
				FD_CLR(client->fd, &rset);
			}
		}
		if (client->status == DONE) {
				goto done;
		}
	}
done:
	buf_destroy(buf);
	tcp_client_destroy(client);
	return 0;
}
